import functools
import logging

import jwt
from flask import request, abort, g

from common.entities import User
from web import settings
from web.common.error_code import ErrorCode

logger = logging.getLogger('web')


def login_required(func):
    @functools.wraps(func)
    def wrap(*args, **kwargs):
        access_token = request.headers.get("Access-Token")
        try:
            user_info = jwt.decode(
                access_token, settings.AUTH_SECRET,
                algorithms=['HS256'], options={"verify_aud": False}
            ) if access_token else None
            user = User.from_dict(user_info) if user_info else None

            if user.id not in settings.ALLOW_USERS:
                raise ErrorCode.PERMISSION_DENIED.to_error()
        except Exception as e:
            logger.warning(f'decode token {access_token} failed: {e}')
            user = None
        logger.info(f'current user is {user}')
        if not user:
            raise ErrorCode.NO_AUTH.to_error()
        g.user = user
        return func(*args, **kwargs)
    return wrap
